<?php

namespace app\service;

use app\model\TaskCategory;
class TaskCategoryServce
{

    private $taskCategory;

    public function __construct()
    {
        $this->taskCategory = new TaskCategory;
    }

    public function list($params = [])
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];

        if(!empty($params['name'])) $where[] = ['name', 'like', '%'.trim($params['name']).'%'];

        if(isset($params['status']) && $params['status']!='' ) $where[]=['status','=',$params['status']];

        $result = $this->taskCategory->order(['sort'=>'desc','updated_at'=>'desc','id' =>'asc'])->where($where)->paginate([
            'list_rows'=> $pageSize,
            'page' => $page
        ])->append(['status_text']);

        return $result;
    }

    public function save($param){
        if(isset($param['id'])){
            unset($param['id']);
        }
        return $this->taskCategory->allowField(['name', 'status', 'sort'])->create($param);
    }

    public function update($id, $param)
    {
        $taskCategory = $this->taskCategory->find($id);
        //数据库存在的字段才更新
        return $taskCategory->allowField(['name', 'status', 'sort'])->save($param);
    }

    public function delete($id)
    {
        return $this->taskCategory->destroy($id);
    }

    /**
     * 获取所有满足特定条件的任务类别
     *
     * 该方法根据提供的参数获取任务类别数据它主要关注于根据状态过滤类别，并按照排序字段和ID进行排序
     *
     * @param array $param 包含过滤条件的参数数组，如状态(status)
     * @return array 返回一个关联数组，键为任务类别ID，值为类别名称
     */
    public function getAll($param)
    {
        // 初始化where条件数组，用于存储查询条件
        $where =[];
        $taskCategory = $this->taskCategory;
        // 检查参数中是否设置了状态，并且状态值不为空
        // 如果条件满足，则将状态等于1作为查询条件之一
        if (isset($param['status']) && $param['status'] != '') {
            $where[]=['status','=',1];
            return $taskCategory->where($where)->order(['sort'=>'desc','id' =>'asc'])->field('name,id')->select();
        }else{
            //包含软删除
            return $taskCategory->order(['sort'=>'desc','id' =>'asc'])->withTrashed()->field('name,id')->select();
        }

    }

    public function getAllKeyValue()
    {
        return $this->taskCategory->where('status',1)->order(['sort'=>'desc','id' =>'asc'])->column('name','id');
    }
}
